//
//  MapViewController.m
//  meituanAddressManagee
//
//  Created by WuXushun on 16/1/25.
//  Copyright © 2016年 wuxushun. All rights reserved.
//

#define mapKey @"872523f26ba22bf344a94e7fe9401c2e"

#import "MapViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <Masonry.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MapPoiCell.h"
#import "poiModel.h"


@interface MapViewController ()<MAMapViewDelegate,AMapSearchDelegate,UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *mapView;
@property (weak, nonatomic) IBOutlet UITableView *listTableview;
@property (strong, nonatomic) MAMapView *map;
@property (strong, nonatomic) AMapSearchAPI *search;
@property (strong, nonatomic) AMapPOIAroundSearchRequest *poiAroundSearch;
@property (strong, nonatomic) NSMutableArray *tempPoiArray;

@property (weak, nonatomic) AMapPOI *temp;
@property (weak, nonatomic) poiModel *tempPoiModel;
@property (strong, nonatomic) UIImageView *point;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initMapView];
    [self initPointView];
    [self initLocalView];
    [self initSearchKit];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    _map.showsUserLocation = YES;
    _map.userTrackingMode =  MAUserTrackingModeFollow;
    [_map setZoomLevel:17.5f animated:YES];
    _map.showsCompass = YES;
    _map.showsLabels = YES;
    _map.rotateCameraEnabled = NO;
    _map.compassOrigin = CGPointMake(self.map.frame.size.width -  _map.compassSize.width - 5, 5);

}

//初始化高德地图
-(void)initMapView{

    [MAMapServices sharedServices].apiKey = mapKey;
    
    _map = [MAMapView new];
    _map.delegate = self;
    _map.translatesAutoresizingMaskIntoConstraints = NO;
    _map.distanceFilter = 10.f;
    _map.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    _map.allowsBackgroundLocationUpdates = NO;
    [self.mapView addSubview:_map];
    
    [_map mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(self.mapView.mas_top).offset(0);
        make.left.equalTo(self.mapView.mas_left).offset(0);
        make.right.equalTo(self.mapView.mas_right).offset(0);
        make.bottom.equalTo(self.mapView.mas_bottom).offset(0);
        
    }];
    
}

//初始化定位点图
-(void)initPointView{

    self.point = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"pointAnnotation@2x"]];
    self.point.translatesAutoresizingMaskIntoConstraints = NO;
    self.point.backgroundColor  =[UIColor clearColor];
    [self.mapView addSubview:self.point];
    
    CGFloat scale = 0.4;
    
    [self.point mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.mapView.mas_centerX);
        make.centerY.equalTo(self.mapView.mas_centerY).offset(- 62.5 * scale + 12);
        make.width.mas_equalTo(50 * scale);
        make.height.mas_equalTo(62.5 * scale);
        
    }];

}


//初始化定位我视图
-(void)initLocalView{

    UIButton *local = [UIButton buttonWithType:UIButtonTypeCustom];
    local.layer .backgroundColor = [UIColor whiteColor].CGColor;
    local.layer.cornerRadius = 3.f;
    local.layer.borderColor = [UIColor colorWithRed:202.f / 255.f
                                              green:202.f / 255.f
                                               blue:202.f / 255.f
                                              alpha:1.f].CGColor;
    local.layer.borderWidth = 0.5f;
    [self.mapView addSubview:local];
    
    [local mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.width.mas_equalTo(30);
        make.height.mas_equalTo(30);
        make.right.equalTo(self.mapView.mas_right).offset(-5);
        make.bottom.equalTo(self.mapView.mas_bottom).offset(-5);
        
    }];
    
    [local addTarget:self action:@selector(localActive) forControlEvents:UIControlEventTouchUpInside];

    UIImageView *localStand = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"localMe@2x"]];
    localStand.backgroundColor = [UIColor clearColor];
    [local addSubview:localStand];
    
    [localStand mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(18);
        make.centerX.equalTo(local.mas_centerX);
        make.centerY.equalTo(local.mas_centerY);
        
    }];
    
}

-(void)initSearchKit{

    [AMapSearchServices sharedServices].apiKey = mapKey;
    //初始化
    _search = [AMapSearchAPI new];
    _search.delegate = self;

}

-(void)aroundSearchActive:(CLLocationCoordinate2D )localtion withKeywords:(NSString *)keywords{

    if (_poiAroundSearch == nil) {
        
        _poiAroundSearch = [AMapPOIAroundSearchRequest new];
        
    }
    
    if (keywords != nil) {
        
        _poiAroundSearch.keywords = keywords;
        
    }
    _poiAroundSearch.location = [AMapGeoPoint locationWithLatitude:localtion.latitude longitude:localtion.longitude];
    _poiAroundSearch.radius = 3000.f;
    _poiAroundSearch.types = @"商务住宅";
    _poiAroundSearch.sortrule = 0;
    _poiAroundSearch.requireExtension = NO;
    
    //发起周边搜索
    [_search AMapPOIAroundSearch:_poiAroundSearch];

}

//定位我视图事件
-(void)localActive{

    [_map setUserTrackingMode:MAUserTrackingModeFollow animated:YES];

}

- (void)mapViewDidFailLoadingMap:(MAMapView *)mapView withError:(NSError *)error{

    NSLog(@"加载失败");

}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error;{

    NSLog(@"定位失败");

}

- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{

    [self aroundSearchActive:mapView.centerCoordinate withKeywords:nil];

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    
    animation.toValue = [NSNumber numberWithFloat: - 10.f];
    
    animation.duration = 0.25f;
    
    animation.removedOnCompletion = YES;
    
    animation.autoreverses = YES;
    
    animation.fillMode = kCAFillModeForwards;
    
    [self.point.layer addAnimation:animation forKey:@"key"];
    
}

-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{

    if(response.pois.count == 0){
        
        return;
    }
    
    //通过 AMapPOISearchResponse 对象处理搜索结果
//    NSString *strCount = [NSString stringWithFormat:@"count: %d",response.count];
//    NSString *strSuggestion = [NSString stringWithFormat:@"Suggestion: %@", response.suggestion];
//    NSString *strPoi = @"";
//    for (AMapPOI *p in response.pois) {
//        strPoi = [NSString stringWithFormat:@"%@\nPOI: %@", strPoi, p.description];
//    }
//    NSString *result = [NSString stringWithFormat:@"%@ \n %@ \n %@", strCount, strSuggestion, strPoi];
//    NSLog(@"Place: %@", result);

    
    if (self.tempPoiArray == nil) {
        
        self.tempPoiArray = [NSMutableArray new];
        
    }
    
    if (self.tempPoiArray.count > 0) {
        
        [self.tempPoiArray removeAllObjects];
        
    }
    
    for (AMapPOI *obj in response.pois) {
        
        poiModel *temp = [poiModel new];
        temp.name = obj.name;
        temp.address = obj.address;
        [self.tempPoiArray addObject:temp];
        
    }
    [self.listTableview setContentOffset:CGPointMake(0,0) animated:NO];
    [self.listTableview reloadData];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0.1;

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 0.1;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 50;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.tempPoiArray.count;

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *poiCell = @"MapPoiCell";
    
    MapPoiCell *cell = [tableView dequeueReusableCellWithIdentifier:poiCell];
    
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MapPoiCell" owner:self options:nil] lastObject];
        
    }
    
    cell.img.image = indexPath.row == 0 ? [UIImage imageNamed:@"yellowPoint@2x"] : [UIImage imageNamed:@"grayPoint@2x"] ;
    
    cell.title.textColor = indexPath.row == 0 ? [UIColor colorWithRed:241.f / 255.f green:212.f / 255.f blue:29.f / 255.f alpha:1.f] : [UIColor blackColor];
    
    cell.subTitle.textColor = indexPath.row == 0 ? [UIColor colorWithRed:241.f / 255.f green:212.f / 255.f blue:29.f / 255.f alpha:1.f] : [UIColor colorWithRed:184.f / 255.f green:184.f / 255.f blue:184.f / 255.f alpha:1.f];
    
    self.tempPoiModel = [self.tempPoiArray objectAtIndex:indexPath.row];
    
    [cell setDataWithModel:self.tempPoiModel];

    return cell;

}

@end
